from django.db import transaction
from django.shortcuts import render

# Create your views here.
from django.http import JsonResponse
from rest_framework.views import APIView
from allmodels.models import SysDept  # 假设部门模型在 allmodels 中
from login.views import verify_token  # 假设已经有验证 token 的函数
import json
from django.db.models import Q

class UpdateDeptView(APIView):
    def put(self, request, dept_id, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 解析请求体中的 JSON 数据
            data = json.loads(request.body)

            # 查找部门
            dept = SysDept.objects.get(id=dept_id)

            # 更新部门字段
            dept.name = data.get('name', dept.name)
            dept.code = data.get('code', dept.code)
            dept.parent_id = data.get('parentId', dept.parent_id)
            dept.status = data.get('status', dept.status)
            dept.sort = data.get('sort', dept.sort)

            # 保存更新后的部门
            dept.save()

            return JsonResponse({
                'code': '00000',
                'msg': '部门更新成功',
                'data': {
                    'id': dept.id,
                    'name': dept.name,
                    'code': dept.code,
                    'parentId': dept.parent_id,
                    'status': dept.status,
                    'sort': dept.sort
                }
            })

        except SysDept.DoesNotExist:
            return JsonResponse({
                'code': '10006',
                'msg': '部门不存在'
            }, status=404)

        except json.JSONDecodeError:
            return JsonResponse({
                'code': '10007',
                'msg': '请求体格式错误'
            }, status=400)

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)


class DeptListView(APIView):
    def get(self, request, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 获取查询参数
        keywords = request.GET.get('keywords', '')
        status = request.GET.get('status', '')

        # 构建查询条件
        filters = Q()
        if keywords:
            filters &= Q(name__icontains=keywords)
        if status:
            filters &= Q(status=status)

        # 查询部门
        dept_query = SysDept.objects.filter(filters).order_by('sort')

        # 递归构建部门树
        def build_dept_tree(parent_id):
            children = []
            for dept in dept_query.filter(parent_id=parent_id):
                children.append({
                    "id": dept.id,
                    "parentId": dept.parent_id,
                    "name": dept.name,
                    "code": dept.code,
                    "sort": dept.sort,
                    # 如果status为true返回1反之0
                    "status": 1 if dept.status else 0,
                    "children": build_dept_tree(dept.id),
                    "createTime": dept.create_time.strftime('%Y-%m-%d %H:%M:%S') if dept.create_time else None,
                    "updateTime": dept.update_time.strftime('%Y-%m-%d %H:%M:%S') if dept.update_time else None
                })
            return children

        dept_list = build_dept_tree(parent_id=0)

        # 返回数据
        return JsonResponse({
            "code": "00000",
            "data": dept_list,
            "msg": "一切ok"
        })

# class CreateDeptView(APIView):
    def post(self, request, *args, **kwargs):
        # 获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 解析请求体
            data = json.loads(request.body)

            # 验证必填参数
            if 'parentId' not in data:
                return JsonResponse({
                    'code': '10006',
                    'msg': '父部门ID为必填项'
                }, status=400)

            # 在事务中保存部门信息
            with transaction.atomic():
                dept = SysDept(
                    name=data.get('name', ''),
                    code=data.get('code', ''),
                    parent_id=data['parentId'],
                    status=data.get('status', 1),  # 状态默认为1（启用）
                    sort=data.get('sort', 1)  # 排序默认为1
                )
                dept.save()

            return JsonResponse({
                'code': '00000',
                'msg': '部门创建成功',
                'data': {
                    'id': dept.id,
                    'name': dept.name,
                    'code': dept.code,
                    'parentId': dept.parent_id,
                    'status': dept.status,
                    'sort': dept.sort
                }
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': '10007',
                'msg': '请求体格式错误'
            }, status=400)

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)

class DeleteDeptView(APIView):
    def delete(self, request, *args, **kwargs):
        # 获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 从 URL 中获取部门 ID
        dept_ids = kwargs.get('ids', '')
        if not dept_ids:
            return JsonResponse({
                'code': '10006',
                'msg': '部门 ID 不能为空'
            }, status=400)

        # 将逗号分隔的 ID 字符串转换为列表
        dept_ids = dept_ids.split(',')

        try:
            with transaction.atomic():
                # 删除部门以及其子部门
                SysDept.objects.filter(id__in=dept_ids).delete()

            return JsonResponse({
                'code': '00000',
                'data': {},
                'msg': '部门删除成功'
            })
        except Exception as e:
            return JsonResponse({
                'code': '10007',
                'msg': f'删除失败: {str(e)}'
            }, status=500)


class GetDeptFormView(APIView):
    def get(self, request, dept_id, *args, **kwargs):
        # 获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 根据 dept_id 获取部门信息
            dept = SysDept.objects.get(id=dept_id)

            # 返回部门的表单数据
            return JsonResponse({
                'code': '00000',
                'data': {
                    'id': dept.id,
                    'name': dept.name,
                    'code': dept.code,
                    'parentId': dept.parent_id,
                    'status': dept.status,
                    'sort': dept.sort
                },
                'msg': '部门信息获取成功'
            })

        except SysDept.DoesNotExist:
            return JsonResponse({
                'code': '10006',
                'msg': '部门不存在'
            }, status=404)

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)

class DeptOptionsView(APIView):
    def get(self, request, *args, **kwargs):
        # 获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 获取所有顶级部门（没有父部门的）
            top_level_depts = SysDept.objects.filter(parent_id=0)

            # 递归获取子部门
            def get_dept_children(parent_id):
                children = SysDept.objects.filter(parent_id=parent_id)
                result = []
                for child in children:
                    result.append({
                        "value": child.id,
                        "label": child.name,
                        "children": get_dept_children(child.id)  # 递归获取子部门
                    })
                return result

            # 构建顶级部门和子部门的层次结构
            dept_options = []
            for dept in top_level_depts:
                dept_options.append({
                    "value": dept.id,
                    "label": dept.name,
                    "children": get_dept_children(dept.id)
                })

            return JsonResponse({
                "code": "00000",
                "data": dept_options,
                "msg": "一切ok"
            })

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)